#include "buffer.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <pthread.h>
#include <string.h>

int main(int argc, char * argv[]){

  //go past the first argument
  *argv++;
  
  int req_size;
  req_size = sizeof(request);
  request r;  
  
  int file = open(*argv++, O_RDWR | O_CREAT, (mode_t)0600);

  // Read in the arguments
  enum Commands c = get_command(*argv++);
  int account = atoi(*argv++);
  int amount;
 
  if(argc > 3)    amount = atof(*argv++);
  else amount = 0;
 

  // Construct the request from the arguments 
  r = read_request(account, amount, c);
 

  // Create the buffer and map 
  buffer * b;
  void * map;
  map = mmap(NULL,  sizeof(buffer), PROT_READ | PROT_WRITE, MAP_SHARED, file, 0);
  b = (buffer *) map;
  
  sem_wait(&b->full);
  sem_wait(&b->lock);
  int current_request;
  current_request = b->current_request;
  b->requests[current_request] = r;
  b->current_request = current_request +1;
  sem_post(&b->lock); 
  sem_post(&(b->requests[current_request].event));

  printf("%d\n", b->empty);
  
  sem_post(&b->empty);
   printf("%d\n", b->empty);


 
  munmap(map, sizeof(buffer));

}

